<!--
 * 车位管理
 *
-->
<template>
    <div>
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item
                ><i
                    class="iconfont icon-stall-menu"
                    style="margin: 5px; font-size: 22px"
                >
                    车位信息管理</i
                ></el-breadcrumb-item
            >
        </el-breadcrumb>

        <!-- 卡片视图区域 -->
        <el-card>
            <el-row :gutter="20">
                <el-col :span="4">
                    <el-input
                        v-model="queryInfo.carArea"
                        placeholder="请输入停车区域"
                    >
                    </el-input>
                </el-col>
                <el-col :span="4">
                    <el-select
                        v-model="queryInfo.carType"
                        placeholder="请选择车位类型"
                    >
                        <el-option
                            v-for="item in carTypes"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        ></el-option>
                    </el-select>
                </el-col>
                <el-col :span="4">
                    <el-select
                        v-model="queryInfo.carState"
                        placeholder="请选择车位状态"
                    >
                        <el-option
                            v-for="item in carStates"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        ></el-option>
                    </el-select>
                </el-col>
                <el-col :span="2">
                    <el-button
                        size="small"
                        type="success"
                        icon="iconfont icon-search-menu"
                        style="font-size: 18px"
                        @click="getList"
                    >
                        搜索</el-button
                    >
                </el-col>
                <el-col :span="2">
                    <el-button
                        size="small"
                        type="primary"
                        icon="iconfont icon-add-button"
                        style="font-size: 18px"
                        @click="addCar"
                    >
                        新增</el-button
                    >
                </el-col>
            </el-row>

            <el-row :gutter="20">
                <el-col :span="15">
                    <!-- 车位信息区域 -->
                    <el-table v-loading="loading" :data="cars" border stripe>
                        <el-table-column
                            width="50"
                            label="序号"
                            align="center"
                            type="index"
                        ></el-table-column>
                        <el-table-column label="车位号" prop="stallNum" align="center">
                        </el-table-column>
                        <el-table-column
                            label="车位区域"
                            prop="stallArea"
                            align="center"
                        >
                        </el-table-column>
                        <el-table-column
                            label="车位类型"
                            prop="stallType"
                            align="center"
                        >
                        </el-table-column>
                        <el-table-column
                            label="车位状态"
                            prop="stallState"
                            align="center"
                        >
                        </el-table-column>
                        <el-table-column
                            label="车位收费"
                            prop="stallMoney"
                            align="center"
                        >
                            <template slot-scope="scope">
                                {{ scope.row.stallMoney }}元/时
                            </template>
                        </el-table-column>
                        <el-table-column
                            label="操作"
                            align="center"
                            width="200"
                            fixed="right"
                        >
                            <template slot-scope="scope">
                                <el-button
                                    @click="toEdit(scope.row)"
                                    type="primary"
                                    circle
                                    ><i
                                        class="iconfont icon-edit-button"
                                        style="font-size: 22px"
                                    ></i
                                ></el-button>
                                <el-button
                                    @click="carDelete(scope.row.sid)"
                                    type="danger"
                                    circle
                                    ><i
                                        class="iconfont icon-del-button"
                                        style="font-size: 22px"
                                    ></i
                                ></el-button>
                            </template>
                        </el-table-column>
                    </el-table>

                    <el-pagination
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page="queryInfo.pagenum"
                        :page-sizes="[5, 10, 15, 20]"
                        :page-size="queryInfo.pageSize"
                        layout="total, sizes, prev, pager, next"
                        :total="total"
                    >
                    </el-pagination>
                </el-col>
                
                <el-col :span="9">
                    <!-- 右侧车位状态可视化区域 -->
                    <div class="parking-visualization-container">
                        <div class="parking-header">
                            <h3>车位状态可视化</h3>
                            <div class="parking-controls">
                                <el-select v-model="selectedArea" placeholder="选择区域" size="small">
                                    <el-option 
                                        v-for="area in parkingAreas" 
                                        :key="area" 
                                        :label="area" 
                                        :value="area">
                                    </el-option>
                                </el-select>
                            </div>
                        </div>
                        
                        <div class="parking-legend">
                            <span class="legend-item">
                                <span class="status-indicator available"></span> 空闲中
                            </span>
                            <span class="legend-item">
                                <span class="status-indicator occupied"></span> 已停车
                            </span>
                            <span class="legend-item">
                                <span class="status-indicator disabled"></span> 维修中
                            </span>
                        </div>
                        
                        <div class="parking-layout">
                            <!-- 车位网格（支持拖拽） -->
                            <div class="parking-grid">
                                <div 
                                    v-for="stall in filteredStalls" 
                                    :key="stall.sid"
                                    class="parking-stall"
                                    :class="[
                                        getStallClass(stall), 
                                        {'fixed-stall': stall.stallType === '固定车位'}
                                    ]"
                                    @click="showStallDetails(stall)"
                                >
                                    <span class="stall-number">{{ stall.stallNum }}</span>
                                </div>
                            </div>
                            
                            <!-- 通道 -->
                            <div class="parking-lane">
                                <span>车道</span>
                            </div>
                            
                            <!-- 剩余空位统计 -->
                            <div class="parking-stats">
                                <el-progress 
                                    :percentage="getAvailablePercentage" 
                                    :format="formatAvailablePercentage"
                                    :stroke-width="18"
                                    :color="availableProgressColor">
                                </el-progress>
                                <div class="stats-text">
                                    空闲车位：{{ availableCount }}/{{ totalParkingCount }}
                                </div>
                            </div>
                        </div>
                    </div>
                </el-col>
            </el-row>
        </el-card>
        <el-dialog
            title="新增车位"
            :visible.sync="addShow"
            width="500px"
            center
            @close="addClose"
        >
            <!-- 内容主题区域 -->
            <el-form
                :model="registerCar"
                status-icon
                :rules="registerRules"
                ref="registerRules"
                label-width="100px"
                class="demo-ruleForm"
            >
                <el-form-item
                    label="车位号"
                    prop="stallNum"
                    class="is-required"
                >
                    <el-input
                        v-model="registerCar.stallNum"
                        placeholder="请输入车位号"
                        style="width: 300px"
                    ></el-input>
                </el-form-item>
                <el-form-item
                    label="车位区域"
                    prop="stallArea"
                    class="is-required"
                >
                    <el-input
                        v-model="registerCar.stallArea"
                        placeholder="请输入车位区域"
                    >
                    </el-input>
                </el-form-item>
                <el-form-item
                    label="车位类型"
                    prop="stallType"
                    class="is-required"
                >
                    <el-select
                        v-model="registerCar.stallType"
                        placeholder="请选择车位类型"
                    >
                        <el-option
                            v-for="item in carTypes"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item
                    label="收费标准"
                    prop="feeId"
                    class="is-required"
                >
                    <el-select
                        v-model="registerCar.feeId"
                        placeholder="请选择收费标准"
                        style="width: 100%"
                    >
                        <el-option
                            v-for="item in feeSettings"
                            :key="item.id"
                            :label="`${item.carType} (${item.money}元/时 - ${item.moneyDesc})`"
                            :value="item.id"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>

            <!-- 底部区域 -->
            <span slot="footer" class="dialog-footer">
                <el-button @click="addClose">取 消</el-button>
                <el-button type="primary" @click="submitForm('registerRules')"
                    >确认添加</el-button
                >
            </span>
        </el-dialog>

        <el-dialog
            title="修改车位"
            :visible.sync="editShow"
            width="500px"
            center
            @close="editClose"
        >
            <!-- 内容主题区域 -->
            <el-form
                :model="editCar"
                status-icon
                :rules="registerRules"
                ref="registerRules"
                label-width="100px"
                class="demo-ruleForm"
            >
                <el-form-item
                    label="车位号"
                    prop="stallNum"
                    class="is-required"
                >
                    <el-input
                        v-model="editCar.stallNum"
                        placeholder="请输入车位号"
                        style="width: 300px"
                    ></el-input>
                </el-form-item>
                <el-form-item
                    label="车位区域"
                    prop="stallArea"
                    class="is-required"
                >
                    <el-input
                        v-model="editCar.stallArea"
                        placeholder="请输入车位区域"
                    >
                    </el-input>
                </el-form-item>
                <el-form-item
                    label="车位类型"
                    prop="stallType"
                    class="is-required"
                >
                    <el-select
                        v-model="editCar.stallType"
                        placeholder="请选择车位类型"
                    >
                        <el-option
                            v-for="item in carTypes"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item
                    label="收费标准"
                    prop="feeId"
                    class="is-required"
                >
                    <el-select
                        v-model="editCar.feeId"
                        placeholder="请选择收费标准"
                        style="width: 100%"
                    >
                        <el-option
                            v-for="item in feeSettings"
                            :key="item.id"
                            :label="`${item.carType} (${item.money}元/时 - ${item.moneyDesc})`"
                            :value="item.id"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>

            <!-- 底部区域 -->
            <span slot="footer" class="dialog-footer">
                <el-button @click="editClose">取 消</el-button>
                <el-button
                    type="primary"
                    @click="editSend('registerRules')"
                    icon="iconfont icon-r-yes"
                >
                    确认修改</el-button
                >
            </span>
        </el-dialog>
        
        <!-- 车位详情弹窗 -->
        <el-dialog
            title="车位详情"
            :visible.sync="stallDetailVisible"
            width="30%"
            center
        >
            <div v-if="selectedStall" class="stall-details">
                <div class="detail-item">
                    <span class="detail-label">车位号：</span>
                    <span class="detail-value">{{ selectedStall.stallNum }}</span>
                </div>
                <div class="detail-item">
                    <span class="detail-label">区域：</span>
                    <span class="detail-value">{{ selectedStall.stallArea }}</span>
                </div>
                <div class="detail-item">
                    <span class="detail-label">类型：</span>
                    <span class="detail-value">{{ selectedStall.stallType }}</span>
                </div>
                <div class="detail-item">
                    <span class="detail-label">状态：</span>
                    <span class="detail-value" :class="getStatusTextClass(selectedStall)">
                        {{ selectedStall.stallState }}
                    </span>
                </div>
                <div class="detail-item">
                    <span class="detail-label">收费标准：</span>
                    <span class="detail-value">{{ selectedStall.stallMoney }}元/时</span>
                </div>
                <div class="detail-item" v-if="selectedStall.feeDetails">
                    <span class="detail-label">收费说明：</span>
                    <span class="detail-value">{{ selectedStall.feeDetails.moneyDesc }}</span>
                </div>
                <div class="detail-actions" v-if="selectedStall.stallState === '空闲中'">
                    <el-button type="primary" size="small" @click="useStall(selectedStall.sid)">
                        预定此车位
                    </el-button>
                </div>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import axios from "axios";
export default {
    data() {
        return {
            total: 0,
            loading: true,
            queryInfo: {
                carArea: "",
                carType: "",
                carState: "",
                pagenum: 1,
                pageSize: 6,
            },
            cars: [],
            registerCar: {
                stallNum: "",
                stallArea: "",
                stallType: "",
                feeId: null
            },
            editCar: {
                sid: "",
                stallNum: "",
                stallArea: "",
                stallType: "",
                feeId: null
            },
            editShow: false,
            uid: undefined,
            addShow: false,
            registerRules: {
                stallNum: [
                    {
                        required: true,
                        message: "请输入车牌号",
                        trigger: "blur",
                    },
                ],
                stallArea: [
                    {
                        required: true,
                        message: "请输入车位区域",
                        trigger: "blur",
                    },
                ],
                stallType: [
                    {
                        required: true,
                        message: "请选择车位类型",
                        trigger: "blur",
                    },
                ],
            },
            carTypes: [
                {
                    value: null,
                    label: "全部",
                },
                {
                    value: "临时车位",
                    label: "临时车位",
                },
                {
                    value: "固定车位",
                    label: "固定车位",
                },
            ],
            carStates: [
                {
                    value: null,
                    label: "全部",
                },
                {
                    value: "已停车",
                    label: "已停车",
                },
                {
                    value: "空闲中",
                    label: "空闲中",
                },
            ],
            // 车位可视化相关数据
            selectedArea: "全部",
            stallDetailVisible: false,
            selectedStall: null,
            feeSettings: [], // 存储收费标准列表
        };
    },
    computed: {
        // 获取所有车位区域列表
        parkingAreas() {
            const areas = ["全部"];
            // 从车位数据中提取出所有区域
            this.cars.forEach(car => {
                if (car.stallArea && !areas.includes(car.stallArea)) {
                    areas.push(car.stallArea);
                }
            });
            return areas;
        },
        
        // 根据选择的区域过滤车位
        filteredStalls() {
            if (this.selectedArea === "全部") {
                return this.cars;
            } else {
                return this.cars.filter(car => car.stallArea === this.selectedArea);
            }
        },
        
        // 计算可用车位数量
        availableCount() {
            return this.filteredStalls.filter(stall => stall.stallState === "空闲中").length;
        },
        
        // 计算总车位数
        totalParkingCount() {
            return this.filteredStalls.length;
        },
        
        // 计算可用百分比
        getAvailablePercentage() {
            if (this.totalParkingCount === 0) return 0;
            return Math.round((this.availableCount / this.totalParkingCount) * 100);
        },
        
        // 根据可用率动态改变进度条颜色
        availableProgressColor() {
            const percentage = this.getAvailablePercentage;
            if (percentage < 20) return '#F56C6C';
            if (percentage < 50) return '#E6A23C';
            return '#67C23A';
        }
    },
    methods: {
        getList() {
            axios
                .post("/stall/pageStall", this.queryInfo)
                .then((res) => {
                    this.loading = false;
                    this.total = res.data.data.total;
                    this.cars = res.data.data.records;
                    
                    // 加载车位关联的费率详情
                    this.loadFeeDetailsForStalls();
                });
        },
        handleSizeChange(newSize) {
            this.queryInfo.pageSize = newSize;
            this.getList();
        },
        handleCurrentChange(newPage) {
            this.queryInfo.pagenum = newPage;
            this.getList();
        },
        addCar() {
            for (let item in this.registerCar) {
                this.registerCar[item] = "";
            }
            this.registerCar.feeId = null;
            if (this.carTypes[0].label == "全部") {
                this.carTypes.shift();
            }
            this.addShow = true;
        },
        addClose() {
            if (this.carTypes[0].label != "全部") {
                this.carTypes.unshift({ value: null, label: "全部" });
            }
            this.addShow = false;
            this.$nextTick(() => {
                this.$refs.registerRules.resetFields();
            });
        },
        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.loading = true;
                    axios
                        .post("/stall/add", this.registerCar)
                        .then((res) => {
                            this.loading = false;
                            if (res.data.data.flag) {
                                // /^[A-Za-z0-9]+$/
                                this.$message.success("添加成功！");
                                this.getList();
                                this.addShow = false;
                            } else {
                                this.$message.error(res.data.data.msg);
                            }
                        });
                } else {
                    return false;
                }
            });
        },
        toEdit(car) {
            if (this.carTypes[0].label == "全部") {
                this.carTypes.shift();
            }
            this.editCar.sid = car.sid;
            this.editCar.stallArea = car.stallArea;
            this.editCar.stallNum = car.stallNum;
            this.editCar.stallType = car.stallType;
            this.editCar.feeId = car.feeId;
            this.editShow = true;
        },
        editClose() {
            if (this.carTypes[0].label != "全部") {
                this.carTypes.unshift({ value: null, label: "全部" });
            }

            this.editShow = false;
            this.$nextTick(() => {
                this.$refs.registerRules.resetFields();
            });
        },
        editSend(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.loading = true;
                    axios
                        .post("/stall/update", this.editCar)
                        .then((res) => {
                            this.loading = false;
                            if (res.data.data.flag) {
                                this.$message.success("更新成功");
                                this.getList();
                                this.editShow = false;
                            } else {
                                this.$message.error(res.data.data.msg);
                            }
                        });
                } else {
                    // console.log('error submit!!');
                    return false;
                }
            });
        },
        async useStall(sid) {
            const re = await this.$confirm(
                "此操作将预定该车位, 是否继续?",
                "提示",
                {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                }
            ).catch((err) => err);
            // console.log(re)
            if (re != "confirm") {
                this.$message.info("已取消预定！");
            } else {
                axios
                    .get(
                        "/stall/orderStall?uid=" + this.uid + "&sid=" + sid
                    )
                    .then((res) => {
                        if (res.data.data) {
                            this.$message.success("预定成功！");
                            this.getList();
                            // 如果是从详情窗口预定的，关闭详情窗口
                            if (this.stallDetailVisible) {
                                this.stallDetailVisible = false;
                            }
                        } else {
                            this.$message.error("预定失败！");
                        }
                    });
            }
        },
        async carDelete(sid) {
            const re = await this.$confirm(
                "此操作将永久删除该车位, 是否继续?",
                "提示",
                {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                }
            ).catch((err) => err);
            if (re != "confirm") {
                this.$message.info("已取消删除！");
            } else {
                axios.get("/stall/del?sid=" + sid).then((res) => {
                    if (res.data.data) {
                        this.$message.success("删除成功！");
                        this.getList();
                    } else {
                        this.$message.error("删除失败，青虫性操作！");
                    }
                });
            }
        },
        
        // 车位可视化相关方法
        
        // 获取车位状态样式类
        getStallClass(stall) {
            if (stall.stallState === "已停车") {
                return "occupied";
            } else if (stall.stallState === "空闲中") {
                return "available";
            } else {
                return "disabled";
            }
        },
        
        // 显示车位详情
        showStallDetails(stall) {
            this.selectedStall = stall;
            
            // 如果车位有关联的费率设置，显示相关信息
            if (this.feeSettings.length > 0 && stall.stallMoney) {
                // 尝试通过费率金额和车辆类型匹配费率设置
                const feeDetail = this.feeSettings.find(fee => 
                    parseFloat(fee.money) === stall.stallMoney && 
                    fee.carType === stall.stallType);
                    
                if (feeDetail) {
                    this.$set(stall, 'feeDetails', feeDetail);
                }
            }
            
            this.stallDetailVisible = true;
        },
        
        // 获取状态文本样式
        getStatusTextClass(stall) {
            if (stall.stallState === "已停车") {
                return "status-occupied";
            } else if (stall.stallState === "空闲中") {
                return "status-available";
            } else {
                return "status-disabled";
            }
        },
        
        // 格式化可用百分比显示
        formatAvailablePercentage(percentage) {
            return `${percentage}% 可用`;
        },
        
        // 加载费率设置列表
        loadFeeSettings() {
            axios.get("/fee-setting/list").then(res => {
                if (res.data && res.data.data) {
                    this.feeSettings = res.data.data;
                }
            }).catch(error => {
                console.error("获取费率设置失败:", error);
            });
        },
        
        // 为车位加载费率详情
        loadFeeDetailsForStalls() {
            // 如果费率设置已加载
            if (this.feeSettings.length > 0) {
                this.cars.forEach(stall => {
                    if (stall.stallMoney) {
                        // 查找金额匹配的费率设置
                        const feeDetail = this.feeSettings.find(fee => 
                            parseFloat(fee.money) === stall.stallMoney && 
                            fee.carType === stall.stallType);
                            
                        if (feeDetail) {
                            this.$set(stall, 'feeDetails', feeDetail);
                            // 设置 feeId 用于编辑表单
                            stall.feeId = feeDetail.id;
                        }
                    }
                });
            }
        },
    },
    mounted() {
        this.getList();
        // 加载费率设置
        this.loadFeeSettings();
        // 从sessionStorage获取用户ID
        this.uid = window.sessionStorage.getItem('token');
    },
};
</script>

<style scoped>
/* 车位可视化样式 */
.parking-visualization-container {
    background-color: #f9fafc;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    padding: 15px;
    height: 100%;
}

.parking-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    padding-bottom: 10px;
    border-bottom: 1px solid #ebeef5;
}

.parking-header h3 {
    margin: 0;
    color: #303133;
    font-size: 18px;
}

.parking-legend {
    display: flex;
    margin-bottom: 15px;
    padding: 8px;
    background-color: #f5f7fa;
    border-radius: 4px;
}

.legend-item {
    display: flex;
    align-items: center;
    margin-right: 15px;
}

.status-indicator {
    display: inline-block;
    width: 16px;
    height: 16px;
    border-radius: 4px;
    margin-right: 5px;
}

.status-indicator.available {
    background-color: #67C23A;
}

.status-indicator.occupied {
    background-color: #F56C6C;
}

.status-indicator.disabled {
    background-color: #909399;
}

.parking-layout {
    height: calc(100% - 80px);
    overflow-y: auto;
    padding: 10px;
    background-color: #fff;
    border-radius: 4px;
    border: 1px solid #ebeef5;
}

.entrance-exit {
    display: flex;
    justify-content: space-between;
    margin-bottom: 15px;
}

.entrance, .exit {
    padding: 5px 10px;
    background-color: #409EFF;
    color: white;
    border-radius: 4px;
}

.parking-grid {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    margin-bottom: 15px;
}

.parking-stall {
    position: relative;
    width: 60px;
    height: 90px;
    border: 2px solid #dcdfe6;
    border-radius: 4px;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    transition: all 0.3s;
}

.parking-stall:hover {
    transform: scale(1.05);
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.parking-stall.available {
    background-color: rgba(103, 194, 58, 0.2);
    border-color: #67C23A;
}

.parking-stall.occupied {
    background-color: rgba(245, 108, 108, 0.2);
    border-color: #F56C6C;
}

.parking-stall.disabled {
    background-color: rgba(144, 147, 153, 0.2);
    border-color: #909399;
}

.fixed-stall {
    border-width: 3px;
}

.stall-number {
    font-size: 14px;
    font-weight: bold;
}

.parking-lane {
    height: 30px;
    background-color: #e4e7ed;
    display: flex;
    justify-content: center;
    align-items: center;
    margin: 15px 0;
    border-radius: 4px;
    color: #606266;
}

.parking-stats {
    margin-top: 15px;
    padding: 10px;
    background-color: #f5f7fa;
    border-radius: 4px;
}

.stats-text {
    margin-top: 10px;
    text-align: center;
    font-weight: bold;
}

/* 车位详情弹窗样式 */
.stall-details {
    padding: 10px;
}

.detail-item {
    margin-bottom: 10px;
    display: flex;
}

.detail-label {
    width: 100px;
    font-weight: bold;
    color: #606266;
}

.detail-value {
    flex: 1;
}

.status-occupied {
    color: #F56C6C;
}

.status-available {
    color: #67C23A;
}

.status-disabled {
    color: #909399;
}

.detail-actions {
    margin-top: 20px;
    text-align: center;
}

/* 禁用未使用的入口/出口样式 */
.entrance-exit {
    display: none;
}

.parking-controls {
    display: flex;
    align-items: center;
}
</style>
